package com.zhugy.comparecode.asm;

import com.zhugy.comparecode.BaseCodeLine;
import com.zhugy.comparecode.CodeLine;
import com.zhugy.comparecode.CompareResult;
import com.zhugy.comparecode.util.CommonUtils;

public class CommandLine extends BaseCodeLine implements CodeLine {
	
	String command;
	String[] operands;

	public CommandLine(int index, String command, String[] operands) {
		super();
		this.index = index;
		this.command = command;
		if (operands != null && operands.length > 0) {
			for (int i = 0; i < operands.length; i++) {
				operands[i] = CommonUtils.trim(operands[i]);
			}
		}
		this.operands = operands;
	}

	public String getCommand() {
		return command;
	}

	public void setCommand(String command) {
		this.command = command;
	}

	public String[] getOperands() {
		return operands;
	}

	public void setOperands(String[] operands) {
		this.operands = operands;
	}

	public CompareResult compareTo(CodeLine l) {
		if (!(l instanceof CommandLine)) {
			return CompareResult.fail("代码类型不一样");
		}
		if (this.command == null) {
			throw new RuntimeException();
		}
		CommandLine a = (CommandLine) l;
		if (!command.equalsIgnoreCase(a.getCommand())) {
			return CompareResult.fail("命令不一样，" + this.command + " VS " + a.getCommand());
		}
		if (this.operands == null || this.operands.length == 0) {
			if (a.getOperands() == null || a.getOperands().length == 0) {
				return CompareResult.success("");
			} else {
				return CompareResult.fail("参数个数不一致！！！ 0 VS " + a.getOperands().length);
			}
		}
		if (a.getOperands() == null || a.getOperands().length == 0) {
			return CompareResult.fail("参数个数不一致！！！ " + this.getOperands().length + " VS 0");
		}
		if (this.operands.length != a.getOperands().length) {
			return CompareResult
					.fail("参数个数不一致！！！ " + this.getOperands().length + " VS " + a.getOperands().length);
		}
		for (int i = 0; i < this.operands.length; i++) {
			String op1 = this.operands[i];
			String op2 = a.getOperands()[i];
			CompareResult result = compareOperand(op1, op2);
			if (!result.isEquals()) {
				return CompareResult.fail("第" + (i + 1) + "个参数不正确   " + result.getMessage());
			}
		}
		return CompareResult.success("");
	}

	private CompareResult compareOperand(String op1, String op2) {
		return CommonUtils.compareContent(op1, op2);
	}
}
